window.onload = function() {
    var subtraction = document.getElementsByClassName("subtraction")[0];
    var add = document.getElementsByClassName("add")[0];
    var number = document.getElementsByClassName("number")[0];
    var count = document.getElementsByClassName("countP");

    //验证表单
    var regtel = /^1[3|4|5|7|8]\d{9}$/; // 手机号码的正则表达式    
    var regnc = /^[\u4e00-\u9fa5]{2,8}$/;
    // 邮箱只允许英文字母、数字、下划线、英文句号、以及中划线组成
    var regemail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    var lTel = document.querySelector('#lTel');
    var lName = document.querySelector('#lName');
    var lEmail = document.querySelector('#lEmail');
    regexp(lTel, regtel); // 手机号码    
    regexp(lName, regnc); // 姓名
    regexp(lEmail, regemail); // 邮箱

    //数量
    var num = number.value;
    //单价
    var price = 25;
    //总价
    var countPrices = 0;

    // 表单验证的函数
    function regexp(ele, reg) {
        ele.onblur = function() {
            if (reg.test(this.value)) {
                // 输入正确时候
                this.nextElementSibling.className = 'success';
                this.nextElementSibling.innerHTML = '<i class="success_icon"></i> 恭喜您输入正确';
            } else {
                //输入错误的时候
                this.nextElementSibling.className = 'error';
                if (ele == lName) {
                    this.nextElementSibling.innerHTML = '<i class="error_icon"></i> 格式不正确，请输入2-8位汉字 ';
                } else if (ele == lTel) {
                    this.nextElementSibling.innerHTML = '<i class="error_icon"></i> 格式不正确，请输入正确的11位手机号 ';
                } else if (ele == lEmail) {
                    this.nextElementSibling.innerHTML = '<i class="error_icon"></i> 格式不正确， 邮箱只允许英文字母、数字、下划线、英文句号、以及中划线组成 ';
                }
            }
        }
    };

    //计算总价的方法
    function countPrice() {
        countPrices = price * num;
        //将总价写到页面上去
        for (var i = 0; i < count.length; i++) {
            count[i].innerHTML = "&yen;" + countPrices;
        }
    }

    //减少商品数量
    subtraction.onclick = function() {
        num--;
        number.value = num;
        if (num <= 1) {
            subtraction.disabled = true;
        }
        add.disabled = false;
        countPrice();
    }


    //增加商品数量
    add.onclick = function() {
        num++;
        number.value = num;
        countPrice();
        if (num == 10) {
            add.disabled = true;
        }
        subtraction.disabled = false;
    }

    //当数量发生变化时
    number.onchange = function() {
        num = number.value;
        if (num >= 10) {
            alert("商品数量不能大于10");
            number.value = 10;
            num = 10;
            add.disabled = true;
            subtraction.disabled = false;
        } else if (num <= 0) {
            alert("当前商品数量最低为1");
            number.value = 1;
            num = 1;
            subtraction.disabled = true;
            add.disabled = false;
        }
        countPrice();
    }
}